<script setup>
import dayjs from 'dayjs';
import { usePickerOption } from '@/views/hooks';
import { useBuildingList, useInsStatics, useInsPieChart, useJCRankChart, useJCTrendChart } from './hooks.js';
import CECharts from '@/components/chart/CECharts.vue';
import Calendar from './components/Calendar.vue';
import InfoList from './components/InfoList.vue';

const emit = defineEmits(['handleRadioChange']);
const type = ref('JC');
const handleRadioChange = val => emit('handleRadioChange', val);
const staticJCList = [
  {
    title: '监测机构（家）',
    staticKey: 'institutionCount',
    subTitle: '年度新增监测机构',
    subKey: 'yearInstitutionCount',
    bg: '#0973eb',
  },
  {
    title: '目标机构数（家）',
    staticKey: 'targetInstitutionCount',
    subTitle: '历史监测机构',
    subKey: 'yearTargetInstitutionCount',
    bg: '#21a726',
  },
  {
    title: '监测投资总额（元）',
    staticKey: 'agreementAmount',
    subTitle: '年度监测项目合同总额',
    subKey: 'yearAgreementAmount',
    bg: '#db0e0e',
  },
  {
    title: '总能耗（吨标煤）',
    staticKey: 'energyValue',
    subTitle: '',
    subKey: '',
    bg: '#de8a0b',
  },
  {
    title: '总碳排（吨二氧化碳）',
    staticKey: 'carbonValue',
    subTitle: '',
    subKey: '',
    bg: '#06adb9',
  },
];

const rangeType = ref({
  d: {
    type: 'daterange',
    fmt: 'yyyy-MM-dd',
    default: [dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().subtract(1, 'day').format('YYYY-MM-DD')],
    pickerOptions: usePickerOption('d'),
  },
  m: {
    type: 'monthrange',
    fmt: 'yyyy-MM',
    default: [dayjs().subtract(6, 'month').format('YYYY-MM'), dayjs().subtract(1, 'month').format('YYYY-MM')],
    pickerOptions: usePickerOption('m'),
  },
  y: { type: 'year', fmt: 'yyyy', default: [dayjs().subtract(2, 'year').format('YYYY'), dayjs().format('YYYY')] },
});

const [buildingList] = useBuildingList('JC');
const [staticData, sLoading] = useInsStatics({ projectType: 'JC' });
const [extraPieOpts, pieLoading] = useInsPieChart('JC');
const [
  activeRank,
  dateRange,
  yearRange,
  engTypes,
  rankParams,
  rLoading,
  barExtraOpts,
  handleDaterange,
  handleYearrange,
  handleRank,
] = useJCRankChart(rangeType);
const [
  dateRangeEC,
  dateRangeCE,
  yearRangeEC,
  yearRangeCE,
  lineExtraOpts1,
  lineExtraOpts2,
  ECParams,
  CEParams,
  ECLoading,
  CELoading,
  engTypeList,
  engTypeList2,
  changeType,
  handleECBuildingCode,
  handleCEBuildingCode,
  handleECDaterange,
  handleCEDaterange,
  handleECYearrange,
  handleCEYearrange,
] = useJCTrendChart(rangeType);

// 开始时间不能大于结束时间
const disabledDateStartRank = ref({
  disabledDate: time => {
    if (yearRange.value.eYear) {
      return dayjs(time) > dayjs(yearRange.value.eYear);
    }
  },
});
const disabledDateStartEC = ref({
  disabledDate: time => {
    if (yearRangeEC.value.eYear) {
      return (
        dayjs(time) > dayjs(yearRangeEC.value.eYear) || dayjs(time) < dayjs(yearRangeEC.value.eYear).subtract(2, 'year')
      );
    }
  },
});
const disabledDateStartCE = ref({
  disabledDate: time => {
    if (yearRangeCE.value.eYear) {
      return (
        dayjs(time) > dayjs(yearRangeCE.value.eYear) || dayjs(time) < dayjs(yearRangeCE.value.eYear).subtract(2, 'year')
      );
    }
  },
});
// 结束时间不能小于开始时间
const disabledDateRank = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRange.value.sYear);
  },
});
const disabledDateEC = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRangeEC.value.sYear) || dayjs(time) > dayjs(yearRangeEC.value.sYear).add(2, 'year');
  },
});
const disabledDateCE = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRangeCE.value.sYear) || dayjs(time) > dayjs(yearRangeCE.value.sYear).add(2, 'year');
  },
});
const showActiveRank = item => {
  return activeRank.value === item ? 'u-primary-bg u-cf5' : null;
};
</script>

<template>
  <div class="app-container">
    <div class="u-df-st u-mb20">
      <div class="u-mr20">
        <el-radio-group v-model="type" size="small" style="margin-bottom: 15px" @input="handleRadioChange">
          <el-radio-button label="JC">监测</el-radio-button>
          <el-radio-button label="TG">托管</el-radio-button>
        </el-radio-group>
        <div class="u-fs20 u-fw-b">欢迎回到能源管理服务系统</div>
      </div>
      <ul class="TGHome-staticList u-df-st">
        <li
          v-for="(item, idx) in staticJCList"
          :key="item.staticKey"
          :class="idx < staticJCList.length - 1 ? 'u-mr20' : null"
          :style="{ backgroundColor: item.bg }"
        >
          <div>
            <div class="u-mb5">{{ item.title }}</div>
            <div class="u-title20 u-fw-b u-fs20">
              <el-skeleton :loading="sLoading" :rows="1" animated>
                <template>
                  <span>{{ staticData?.[item.staticKey] ?? '--' }}</span>
                </template>
              </el-skeleton>
            </div>
          </div>
          <div class="TGHome-staticList-subItem u-title20 u-fs12" :style="{ color: item.bg }">
            <el-skeleton :loading="sLoading" :rows="1" animated>
              <template>
                <span>{{ item.subTitle }} {{ staticData?.[item.subKey] }}</span>
              </template>
            </el-skeleton>
          </div>
        </li>
      </ul>
    </div>
    <div class="u-df-st u-h100">
      <div class="EMHome-left">
        <div class="EMHome-chartBox u-df-st u-mb20">
          <div class="homeChart-subBox u-p20 u-base-fg u-mr20">
            <div class="u-title20 u-fs16 u-prim-text">监测机构行业分类占比</div>
            <CECharts v-loading="pieLoading" :options="extraPieOpts" type="pie" style="height: calc(100% - 20px)" />
          </div>
          <div class="homeChart-subBox u-p20 u-base-fg">
            <div class="u-df-spb u-title20">
              <span class="u-fs16 u-prim-text">机构能耗排名</span>
              <div class="u-df-ed">
                <div :class="showActiveRank('up')" class="chart-sort text-center u-fs14" @click="handleRank('up')">
                  <i class="el-icon-sort-up"></i>
                </div>
                <div :class="showActiveRank('down')" class="chart-sort text-center u-fs14" @click="handleRank('down')">
                  <i class="el-icon-sort-down"></i>
                </div>
                <el-form :model="rankParams" :inline="true" class="u-ml10">
                  <el-form-item prop="energyType">
                    <el-select
                      v-model="rankParams.energyType"
                      placeholder=""
                      size="mini"
                      class="u-mr10"
                      style="width: 120px"
                    >
                      <el-option
                        v-for="item in engTypes ?? []"
                        :key="item.id"
                        :label="item.energyName + '能耗'"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item v-if="rangeType[rankParams.dateType].type !== 'year'">
                    <el-date-picker
                      v-model="dateRange"
                      :type="rangeType[rankParams.dateType].type ?? 'daterange'"
                      :key="rangeType[rankParams.dateType].type ?? 'daterange'"
                      :value-format="rangeType[rankParams.dateType].fmt ?? 'yyyy-MM-dd'"
                      :picker-options="rangeType[rankParams.dateType].pickerOptions"
                      :clearable="false"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      size="mini"
                      align="left"
                      style="width: 240px"
                      @change="handleDaterange"
                    />
                  </el-form-item>
                  <el-form-item v-else>
                    <el-date-picker
                      v-model="yearRange.sYear"
                      type="year"
                      value-format="yyyy"
                      :picker-options="disabledDateStartRank"
                      placeholder="开始年份"
                      size="mini"
                      clearable
                      style="width: 115px"
                      class="u-mr5"
                      @change="handleYearrange"
                    />
                    <el-date-picker
                      v-model="yearRange.eYear"
                      type="year"
                      value-format="yyyy"
                      :picker-options="disabledDateRank"
                      placeholder="结束年份"
                      size="mini"
                      clearable
                      style="width: 115px"
                      @change="handleYearrange"
                    />
                  </el-form-item>
                </el-form>
              </div>
            </div>
            <CECharts v-loading="rLoading" :options="barExtraOpts" type="bar" style="height: calc(100% - 20px)" />
          </div>
        </div>
        <div class="EMHome-chartBox u-p20 u-mb20 u-base-fg">
          <div class="u-title20 u-df-spb">
            <span class="u-fs16 u-prim-text">能耗趋势分析</span>
            <el-form :model="ECParams" :inline="true">
              <el-form-item prop="inId">
                <el-select
                  v-model="ECParams.inId"
                  placeholder="全部机构"
                  size="mini"
                  class="u-mr10"
                  style="width: 200px"
                  clearable
                  @change="handleECBuildingCode"
                >
                  <el-option
                    v-for="item in buildingList ?? []"
                    :key="item.enterpriseCode"
                    :label="item.enterpriseName"
                    :value="item.enterpriseCode"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="energyType" class="u-mr10">
                <el-select v-model="ECParams.energyType" placeholder="" size="mini" class="u-mr10">
                  <el-option
                    v-for="item in engTypeList"
                    :key="item.id"
                    :label="item.energyName + '能耗'"
                    :value="item.id"
                    @click.native="changeType(item)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="rangeType[ECParams.dateType].type !== 'year'">
                <el-date-picker
                  v-model="dateRangeEC"
                  :type="rangeType[ECParams.dateType].type ?? 'daterange'"
                  :key="rangeType[ECParams.dateType].type ?? 'daterange'"
                  :value-format="rangeType[ECParams.dateType].fmt ?? 'yyyy-MM-dd'"
                  :picker-options="rangeType[ECParams.dateType].pickerOptions"
                  :clearable="false"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="mini"
                  align="left"
                  class="u-mr10"
                  style="width: 240px"
                  @change="handleECDaterange"
                />
              </el-form-item>
              <el-form-item v-else>
                <el-date-picker
                  v-model="yearRangeEC.sYear"
                  :picker-options="disabledDateStartEC"
                  :clearable="false"
                  type="year"
                  value-format="yyyy"
                  placeholder="开始年份"
                  size="mini"
                  style="width: 115px"
                  class="u-mr5"
                  @change="handleECYearrange"
                />
                <el-date-picker
                  v-model="yearRangeEC.eYear"
                  :picker-options="disabledDateEC"
                  :clearable="false"
                  type="year"
                  value-format="yyyy"
                  placeholder="结束年份"
                  size="mini"
                  class="u-mr10"
                  style="width: 115px"
                  @change="handleECYearrange"
                />
              </el-form-item>
              <el-form-item prop="dateType">
                <el-radio-group v-model="ECParams.dateType" size="mini">
                  <el-radio-button label="d">日</el-radio-button>
                  <el-radio-button label="m">月</el-radio-button>
                  <el-radio-button label="y">年</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
          <CECharts v-loading="ECLoading" :options="lineExtraOpts1" type="line" style="height: calc(100% - 20px)" />
        </div>
        <div class="EMHome-chartBox u-p20 u-base-fg">
          <div class="u-title20 u-df-spb">
            <span class="u-fs16 u-prim-text">碳排趋势分析</span>
            <el-form :model="CEParams" :inline="true">
              <el-form-item prop="inId">
                <el-select
                  v-model="CEParams.inId"
                  placeholder="全部机构"
                  size="mini"
                  style="width: 200px"
                  class="u-mr10"
                  clearable
                  @change="handleCEBuildingCode"
                >
                  <el-option
                    v-for="item in buildingList ?? []"
                    :key="item.enterpriseCode"
                    :label="item.enterpriseName"
                    :value="item.enterpriseCode"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="energyType" class="u-mr10">
                <el-select v-model="CEParams.energyType" placeholder="" size="mini" class="u-mr10">
                  <el-option
                    v-for="item in engTypeList2 || engTypeList"
                    :key="item.id"
                    :label="item.energyName + '能耗'"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="rangeType[CEParams.dateType].type !== 'year'">
                <el-date-picker
                  v-model="dateRangeCE"
                  :type="rangeType[CEParams.dateType].type ?? 'daterange'"
                  :key="rangeType[CEParams.dateType].type ?? 'daterange'"
                  :value-format="rangeType[CEParams.dateType].fmt ?? 'yyyy-MM-dd'"
                  :picker-options="rangeType[CEParams.dateType].pickerOptions"
                  :clearable="false"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="mini"
                  align="left"
                  class="u-mr10"
                  style="width: 240px"
                  @change="handleCEDaterange"
                />
              </el-form-item>
              <el-form-item v-else>
                <el-date-picker
                  v-model="yearRangeCE.sYear"
                  :picker-options="disabledDateStartCE"
                  :clearable="false"
                  type="year"
                  value-format="yyyy"
                  placeholder="开始年份"
                  size="mini"
                  style="width: 115px"
                  class="u-mr5"
                  @change="handleCEYearrange"
                />
                <el-date-picker
                  v-model="yearRangeCE.eYear"
                  :picker-options="disabledDateCE"
                  :clearable="false"
                  type="year"
                  value-format="yyyy"
                  placeholder="结束年份"
                  size="mini"
                  class="u-mr10"
                  style="width: 115px"
                  @change="handleCEYearrange"
                />
              </el-form-item>
              <el-form-item prop="dateType">
                <el-radio-group v-model="CEParams.dateType" size="mini">
                  <el-radio-button label="d">日</el-radio-button>
                  <el-radio-button label="m">月</el-radio-button>
                  <el-radio-button label="y">年</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
          <CECharts v-loading="CELoading" :options="lineExtraOpts2" type="line" style="height: calc(100% - 20px)" />
        </div>
      </div>
      <div class="EMHome-right">
        <Calendar type="TG" class="home-calendar u-mb20" />
        <InfoList class="home-calendar" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.TGHome-staticList {
  flex: 1;
  > li {
    flex: 1;
    color: #f5f5f5;
    font-size: 14px;
    border-radius: 4px;
    > div:first-of-type {
      padding: 12px;
      padding-bottom: 5px;
    }
  }
  &-subItem {
    background-color: rgba(255, 255, 255, 0.8);
    padding: 0 12px;
    border-radius: 0 0 4px 4px;
  }
  :deep(.el-skeleton.is-animated .el-skeleton__item) {
    background: linear-gradient(
      90deg,
      rgba(242, 242, 242, 0.5) 25%,
      rgba(230, 230, 230, 0.5) 37%,
      rgba(242, 242, 242, 0.5) 63%
    );
  }
}
.chart-sort {
  width: 26px;
  height: 26px;
  line-height: 26px;
  margin-right: 5px;
  border-radius: 2px;
  cursor: pointer;
}
.u-cf5 {
  color: #f5f5f5;
}
.app-dark .chart-sort {
  border: 1px solid #262f48;
}
.app-light .chart-sort {
  border: 1px solid #dcdfe6;
}
:deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 0 !important;
}
:deep(.el-form-item__content) {
  height: 28px;
  line-height: 28px;
}
:deep(.el-radio-button__inner) {
  height: 28px !important;
}
:deep(.el-radio-button--mini .el-radio-button__inner) {
  padding: 7px;
}
</style>
